import json
import uuid
from threading import Thread
from api_server.api_recruit import ApiRecruit
from crawler_core.constant.constants import Constants
from crawler_core.event.task.task_router import TaskRouter
from crawler_core.utils.base_utils import BaseUtils
from crawler_core.utils.redis_utils import RedisUtils
from lib.sys.logger_factory import LoggerFactory
from lib.sys.sys_config import SystemConfig


class EventDown(object):
    logger = LoggerFactory.getLogger("EventDown")

    def __init__(self):
        pass
        pass

    def start(self):
        source = SystemConfig.get_chanel_name_list()
        if not source:
            return
        for i in source:
            down_list = ApiRecruit.resume_down_list(i)
            for data in down_list:
                tenant_id = data.get(Constants.API_PARAM_TENANT_ID)
                is_true = RedisUtils.existEventDownloadLock(tenant_id)
                if not is_true:
                    task_id = Constants.TASK_NAME_DOWNLOAD
                    task_id += "_" + str(uuid.uuid1())
                    EventDown.logger.info("EventDown -- 生成任务 --[%s]--，开始发送事件 ..." % task_id)
                    RedisUtils.addEventDownloadLock(tenant_id, task_id)
                    task = TaskRouter()
                    task.start_download(data, task_id)


class EventSearch(object):
    logger = LoggerFactory.getLogger("EventSearch")

    def __init__(self):
        pass

    def start(self):
        # 判断 渠道是否存在异常

        # 判断 数据是否已经存在(加锁)
        _list = self.get_data()
        # 获取数据 发送二级 分片处理
        for context in _list:
            task_id = context[Constants.CONTEXT_TYPE] \
                      + "#@#" + context[Constants.CONTEXT_CORP_CODE] + "#@#" + context[Constants.CONTEXT_UNION_KEY]
            # 保存任务数据
            RedisUtils.setEventSearchContext(task_id, context)
            # 发送查询分片任务-- 队列实现
            RedisUtils.setEventSearchSecondTask(task_id)

    def get_data(self):
        # 获取关键字
        # _data = ApiRecruit.get_search_keyword()
        _data = {
            'java': ['JCL0000002', 'JCL0000003'],
            'oa': ['JCL0000002']
        }
        temp_arr = []
        _list_search = []
        for keyword in _data:
            corp_code_arr = _data.get(keyword)
            temp_arr.extend(corp_code_arr)
            # 获取 企业 搜索条件详情
            corp_code_str = ','.join(corp_code_arr)
            # _search_condition = ApiRecruit.get_search_info(keyword, corp_code_str)
            _search_condition = {
                'JCL0000002': [{'keyword': 'java', 'city': '上海', 'workYear': '1,3', 'education': '本科'}]
            }
            _list_search.append(_search_condition)
        _set_corp_code = set(temp_arr)
        # 构造数据
        if len(_list_search) > 0:
            return self.init_data(_list_search, _set_corp_code)
        return None

    def init_data(self, _list_search, _set_corp_code):
        # 获取企业账号接口
        corp_code_str = ','.join(_set_corp_code)
        # _account_obj = ApiRecruit.get_search_account(corp_code_str)
        _account_obj = {
            "JCL0000002": {
                "51job": [{"account": "泛微网络SH", "username": "fanwei", "password": "jucailin01"}]
            }
        }
        _list = []
        # 获取
        for _search_obj in _list_search:
            _list_context = self.init_context(_account_obj, _search_obj)
            _list.extend(_list_context)
        return _list

    def init_context(self, _account_obj, _search_obj):
        _list_context = []
        _search_obj = {
            'JCL0000002': [
                {'id': '1111111111111111', 'keyword': 'java', 'city': '上海', 'workYear': '1,5', 'education': '本科'},
                {'id': '2222222222222222', 'keyword': 'python', 'city': '上海', 'workYear': '1,3', 'education': '研究生'},
                {'id': '3333333333333333', 'keyword': 'OA', 'city': '上海', 'workYear': '1,3', 'education': '本科'},
                {'id': '4444444444444444', 'keyword': 'C++', 'city': '上海', 'workYear': '0,1', 'education': '本科'},
                {'id': '5555555555555555', 'keyword': 'PHP', 'city': '上海', 'workYear': '1,3', 'education': '本科'},
                ]
        }
        for key, values in _search_obj.items():
            account_obj = _account_obj.get(key)
            for source, accounts in account_obj.items():
                account = accounts[0]
                for search_condition in values:
                    context = {
                        Constants.CONTEXT_EVENT_TYPE: "search",  # 事件类型
                        Constants.CONTEXT_UNION_KEY: search_condition["id"],  # 事件类型
                        Constants.CONTEXT_TYPE: source,  # 渠道
                        Constants.CONTEXT_CORP_CODE: key,  # 账号唯一标识
                        Constants.CONTEXT_SEARCH_CONDITION: search_condition,  # 条件列表,{}格式
                        Constants.CONTEXT_ACCOUNT: account["account"],  # VIP(公司名)
                        Constants.CONTEXT_USERNAME: account["username"],  # 账号
                        Constants.CONTEXT_PASSWORD: account["password"],  # 密码
                        Constants.CONTEXT_ACCOUNT_LIST: accounts,  # 账号集合
                        Constants.CONTEXT_TOTAL: 5,  # 总数
                        Constants.CONTEXT_PAGE_SIZE: 1,  # 每页数字
                        Constants.CONTEXT_CUR_TOTAL: 0,  # 当前总数
                        Constants.CONTEXT_CUR_PAGE: 1,  # 当前页数
                        Constants.CONTEXT_IS_OVER: 0,  # 是否完成  0未完成  1 完成
                        Constants.CONTEXT_CARD_NUMBER: 0,  # 切片数量
                        Constants.CONTEXT_CARD_COMPLETE: 0  # 切片完成数量
                    }
                    id = BaseUtils.md5(str(context))
                    if id not in RedisUtils.getKeyAll():
                        RedisUtils.setKey(id)
                        _list_context.append(context)
        return _list_context


class EventSearchSecond(object):
    logger = LoggerFactory.getLogger("EventSearchSecond")

    def __init__(self):
        pass

    def start(self):
        # 获取任务
        task_id = RedisUtils.getEventSearchSecondTask()
        if not task_id:
            return
        context = RedisUtils.getEventSearchContext(task_id)
        if not context:
            return
        # 判断 总任务 是够结束, is_over, card_complete
        if 1 == context[Constants.CONTEXT_IS_OVER]:
            return
        total = context[Constants.CONTEXT_TOTAL]
        cur_total = context[Constants.CONTEXT_CUR_TOTAL]
        # 判断 总任务 是够结束, is_over, card_complete
        if total <= cur_total:
            return
        task = TaskRouter()

        task.start_search_second(context, task_id)